package com.yuxin.common.security;

import com.yuxin.common.util.DBUtil;
import com.yuxin.common.util.JsonUtil;
import com.yuxin.common.util.MD5Util;
import com.yuxin.common.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author zehui.zeng
 * @date 13-3-17 下午6:01
 */
public class LoginServlet implements Servlet {

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
	}

	@Override
	public ServletConfig getServletConfig() {
		return null;
	}

	@Override
    public synchronized void  service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException,IOException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String name = request.getParameter("NAME").trim();
        String password = request.getParameter("PASSWORD");
        String yanzheng = request.getParameter("yanzheng").trim();
        String ctx = request.getContextPath();
        String errorMsg = "";// 错误消息
        String redirectUrl = ctx+"/index.jsp?name="+URLEncoder.encode(name,"UTF-8");// 重定向URL
        Connection conn = null;
        String code =  request.getSession().getAttribute("user.randomCode")+"";
        if(!code.equals(yanzheng)){
            errorMsg = "验证码不正确，请重新输入验证码。";
        }else{
            try {
                conn = DBUtil.getConnection();
                Map<String,Object> user = DBUtil.queryUniqueResult(conn,"SELECT * FROM P_USER WHERE USERNAME = ? ",(Object)name);
                if(user != null){
                    String pwd = user.get("PASSWORD").toString();
                    String type = user.get("TYPE").toString();
                    if(!MD5Util.encodePassword(name+password).equals(pwd)){
                        errorMsg = "密码错误!";
                    }else if("3".equals(type)){// 管理员
                        redirectUrl = ctx+"/admin/index.jsp";
                    }else if("2".equals(type)){// 商家
                    	// 商家等待审核状态
                    	Map<String, Object> traderMap = DBUtil.queryUniqueResult(conn, "select t.ID from p_trade t where t.ID = ? and t.STATUS = 1", user.get("SRC_ID"));
                    	if(traderMap != null && traderMap.size() > 0) {
                    		redirectUrl = ctx+"/trader_waiting.jsp";
                    		response.sendRedirect(redirectUrl);
                    		return;
                    	} 
                    	redirectUrl = ctx+"/trader/index.jsp";
                    }else{
                        redirectUrl = ctx+"/index.jsp";
                    }
                    request.getSession().setAttribute("user", user);
                }else{
                    errorMsg = "帐号不存在!";
                }
            }catch (Exception e){
                errorMsg = e.getMessage();
            }finally {
                DBUtil.close(conn);
            }
        }
        if(StringUtils.hasText(errorMsg)){
            redirectUrl += "&error="+ URLEncoder.encode(errorMsg, "UTF-8");
        }
        response.sendRedirect(redirectUrl);
    }

	@Override
	public String getServletInfo() {
		return null;
	}

	@Override
	public void destroy() {
	}

}
